package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.IProjectAuthorizeService;
import com.ruoyi.system.service.IThingsBoardTenantService;
import com.ruoyi.system.domain.DeviceTerminal;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.IDeviceTerminalService;
import com.ruoyi.system.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/device.v2")
public class DeviceTerminalController extends BaseController
{
    @Autowired
    IThingsBoardTenantService thingsBoardTenantService;

    @Autowired
    IProductService productService;

    @Autowired
    private IDeviceTerminalService deviceTerminalService;
    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;

    private AjaxResult checkExistance(DeviceTerminal deviceTerminal) {
        Map<String, Object> existance = deviceTerminalService.findExistance(deviceTerminal);
        if (existance != null) {
            Object name_exists = existance.get("name_exists");
            if (name_exists != null && Integer.parseInt(name_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "终端名称已经存在");
            }
            Object number_exists = existance.get("number_exists");
            if (number_exists != null && Integer.parseInt(number_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "终端序号已经存在");
            }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:device:terminal:list')")
    @GetMapping(value = "/{id}/terminals/list", produces = "application/json;charset=UTF-8")
    public Object indexTerminals(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        //TODO 验证当前产品是否属于当前用户所建的项目
        projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),id);

        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("device_id", id);
        queryVo.filters.put("company_id", companyId);
        startPage();
        List<DeviceTerminal> deviceTerminals= deviceTerminalService.index(queryVo);
        return getDataTable(deviceTerminals);
    }

    @PreAuthorize("@ss.hasPermi('system:device:terminal:enum')")
    @GetMapping(value = "/{id}/terminals/enum", produces = "application/json;charset=UTF-8")
    public AjaxResult enumerateTerminals(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        //TODO 验证当前产品是否属于当前用户所建的项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),id);

        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("device_id", id);
        return AjaxResult.success(deviceTerminalService.enumerate(queryVo));
    }

    @PreAuthorize("@ss.hasPermi('system:device:terminal:query')")
    @GetMapping(value = "/terminal/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieveTerminal(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        DeviceTerminal deviceTerminal = deviceTerminalService.retrieve(queryVo);
        if (deviceTerminal == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        //TODO 验证当前产品是否属于当前用户所建的项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),deviceTerminal.getDeviceId());

        return AjaxResult.success(deviceTerminal);
    }

    @PreAuthorize("@ss.hasPermi('system:device:terminal:edit')")
    @Log(title = "产品终端", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/terminal/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult editTerminal(@RequestBody @Validated(Update.class) DeviceTerminal deviceTerminal) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", deviceTerminal.getId());
        DeviceTerminal target = deviceTerminalService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        //TODO 验证当前产品是否属于当前用户所建的项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),target.getDeviceId());

        deviceTerminal.setDeviceId(target.getDeviceId());
        deviceTerminal.setProductTerminalId(target.getProductTerminalId());
        deviceTerminal.setCompanyId(target.getCompanyId());
        AjaxResult ret = checkExistance(deviceTerminal);
        if (ret != null) {
            return ret;
        }
        if (deviceTerminalService.update(deviceTerminal)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
